import { createRouter, createWebHistory } from 'vue-router'
import store from '../store/index'

const routes = [
  // 登录页面
  {
    path: '/login',
    name: 'login',
    component: () => import("../views/pages/login.vue"),
  },
  {
    // 主页面
    path: '/',
    name: 'layout',
    component: () => import('../views/Layout/LayOut.vue'),
    redirect: '/index',
    // 子路由
    children: [
      {
        path: '/index',
        name: 'index',
        component: () => import("../views/pages/index.vue")
      },
      {
        path: '/roles',
        name: 'roles',
        component: () => import("../views/pages/rolesList.vue")
      },
      {
        path: '/user',
        name: 'user',
        component: () => import("../views/pages/userList.vue")
      },
      {
        path: '/goods',
        name: 'goods',
        component: () => import("../views/pages/goodsList.vue")
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),//History模式
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // console.log('store', store.state.uInfo);
  const uInfo = store.state.uInfo.userInfo
  if (!uInfo.username) {
    // 未登录 跳转到login页面
    if (to.path === '/login') {
      next()
      return
    }
    next("/login")
  } else {
    next()
  }
})

export default router
